package com.iflytek.read.util;

import android.content.Context;
import android.util.Log;

import com.iflytek.read.BuildConfig;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class LogUtil {
    private static boolean isDebug = BuildConfig.DEBUG;
    private static final String LOG_DIR = "logs";
    private static final long MAX_FILE_SIZE = (long) (20 * 1024); // 20kb
    private static final long ONE_HOUR_IN_MILLIS = 60 * 60 * 1000L;
    private static Context appContext;
    private static final long THREE_DAYS_IN_MILLIS = 3 * 24 * 60 * 60 * 1000L;
    
    public static void init(Context context) {
        appContext = context.getApplicationContext();
        createLogDir();
        cleanOldLogs(); // Clean old logs on initialization
    }
    
    private static void createLogDir() {
        File logDir = new File(appContext.getFilesDir(), LOG_DIR);
        if (!logDir.exists()) {
            logDir.mkdirs();
        }
    }
    
    private static String getLogFileName() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        String baseFileName = sdf.format(new Date());
        File logDir = new File(appContext.getFilesDir(), LOG_DIR);
        File[] existingFiles = logDir.listFiles((dir, name) -> name.startsWith(baseFileName));
        
        long now = System.currentTimeMillis();
        
        if (existingFiles != null) {
            // Check for files from today
            for (File file : existingFiles) {
                // If file size is under limit and last modified within 1 hour
                if (file.length() < MAX_FILE_SIZE && 
                    (now - file.lastModified() < ONE_HOUR_IN_MILLIS)) {
                    return file.getName();
                }
            }
        }
        
        // Create new file with current timestamp
        SimpleDateFormat fullSdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.getDefault());
        return fullSdf.format(new Date()) + ".log";
    }
    
    private static void writeToFile(String level, String tag, String msg) {
        if (appContext == null) return;
        if (!LogUtil.isDebug) return;

        try {
            File logDir = new File(appContext.getFilesDir(), LOG_DIR);
            File logFile = new File(logDir, getLogFileName());
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());
            String timeStamp = sdf.format(new Date());
            String logLine = String.format("%s %s/%s: %s\n", timeStamp, level, tag, msg);
            
            FileWriter writer = new FileWriter(logFile, true);
            writer.append(logLine);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            Log.e("LogUtil", "Error writing to log file: " + e.getMessage());
        }
    }

    public static void v(String tag, String msg) {
        if(isDebug){
            Log.v(tag, msg);
        }
        writeToFile("V", tag, msg);
    }

    public static void d(String tag, String msg) {
        if(isDebug){
            Log.d(tag, msg);
        }
        writeToFile("D", tag, msg);
    }

    public static void i(String tag, String msg) {
        if(isDebug){
            Log.i(tag, msg);
        }
        writeToFile("I", tag, msg);
    }

    public static void e(String tag, String msg) {
        if(isDebug){
            Log.e(tag, msg);
        }
        writeToFile("E", tag, msg);
    }

    public static void e(String tag, String msg, Throwable throwable) {
        if(isDebug){
            Log.e(tag, msg + " " + throwable.getMessage());
        }
        writeToFile("E", tag, msg + " " + throwable.getMessage());
    }

    public static void w(String tag, String msg) {
        if(isDebug){
            Log.w(tag, msg);
        }
        writeToFile("W", tag, msg);
    }

    public static File[] getLogFiles() {
        if (appContext == null) return new File[0];
        File logDir = new File(appContext.getFilesDir(), LOG_DIR);
        if (!logDir.exists()) return new File[0];
        return logDir.listFiles((dir, name) -> name.endsWith(".log"));
    }
    
    public static String readLogFile(File file) {
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
        } catch (IOException e) {
            Log.e("LogUtil", "Error reading log file: " + e.getMessage());
        }
        return content.toString();
    }

    public static void cleanOldLogs() {
        if (appContext == null) return;
        
        File logDir = new File(appContext.getFilesDir(), LOG_DIR);
        if (!logDir.exists()) return;
        
        long now = System.currentTimeMillis();
        File[] files = logDir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (now - file.lastModified() > THREE_DAYS_IN_MILLIS) {
                    if (file.delete()) {
                        Log.i("LogUtil", "Deleted old log file: " + file.getName());
                    }
                }
            }
        }
    }

    public static void deleteAllLogs() {
        if (appContext == null) return;
        
        File logDir = new File(appContext.getFilesDir(), LOG_DIR);
        if (!logDir.exists()) return;
        
        File[] files = logDir.listFiles();
        if (files != null) {
            for (File file : files) {
                file.delete();
            }
        }
    }
}
